package com.judian.smart.activity;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.judian.smart.model.GateWay;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.judian.smart.R;
import com.judian.smart.adapter.FamilyAdapter;
import com.judian.smart.adapter.GateWayAdapter;
import com.judian.smart.base.MyApplication;
import com.judian.smart.constant.Constants;
import com.judian.smart.decoration.LinearSpacingItemDecoration;
import com.judian.smart.factory.GateWayFactory;
import com.judian.smart.interfaces.OnListItemClickListener;
import com.judian.smart.model.Archive;
import com.judian.smart.util.CaseFileUtil;
import com.judian.smart.util.JSONHelper;
import com.judian.smart.util.MasterUtils;
import com.judian.smart.util.ProgressDialogUtils;
import com.judian.smart.util.QRCodeUtils;
import com.judian.smart.util.RetrofitUtil;
import com.judian.smart.util.ToastPlus;
import com.judian.smart.util.ToastUtils;
import com.judian.smart.view.DialogAlert;

import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SpecifiedCloudFamily extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = SpecifiedCloudFamily.class.getSimpleName();

    private String appVersion = MyApplication.getInstance().getAPPVersion();
    private String account = "";
    private String password = "";
    private EditText account_edt;
    private EditText password_edt;
    private LinearLayout keyboard_number;
    private LinearLayout gateway_layout;
    private TextView next_complete;
    private TextView input_one;
    private TextView input_two;
    private TextView input_three;
    private TextView input_four;
    private TextView input_five;
    private TextView input_six;
    private TextView input_seven;
    private TextView input_eight;
    private TextView input_nigh;
    private TextView input_zero;
    private TextView delete;
    private TextView back;
    private Button familysSearchBtn, gatewaySearchBtn;
    private FrameLayout not_find;
    private RecyclerView family_list;
    private RecyclerView gateway_list;
    private FamilyAdapter familyAdapter;
    private SharedPreferences.Editor mEditor;

    private boolean isFamilys = true;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0:
                    ToastPlus.showSuccess(msg.obj.toString());
                    break;
            }
        }
    };


    private void initViewId() {
        account_edt = findViewById(R.id.account_edt);
        password_edt = findViewById(R.id.password_edt);
        next_complete = findViewById(R.id.next_complete);
        input_one = findViewById(R.id.input_one);
        input_two = findViewById(R.id.input_two);
        input_four = findViewById(R.id.input_four);
        input_three = findViewById(R.id.input_three);
        input_five = findViewById(R.id.input_five);
        input_six = findViewById(R.id.input_six);
        input_seven = findViewById(R.id.input_seven);
        input_eight = findViewById(R.id.input_eight);
        input_nigh = findViewById(R.id.input_nigh);
        input_zero = findViewById(R.id.input_zero);
        delete = findViewById(R.id.delete);
        back = findViewById(R.id.back);
        familysSearchBtn = findViewById(R.id.familysSearchBtn);
        family_list = findViewById(R.id.family_list);
        gateway_list = findViewById(R.id.gateway_list);
        gateway_layout = findViewById(R.id.gateway_layout);
        keyboard_number = findViewById(R.id.keybord_number);
        not_find = findViewById(R.id.not_find);
        gatewaySearchBtn = findViewById(R.id.gatewaySearchBtn);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_specified_cloud_family);
        initViewId();
        initEditText();
        setListener();
        initView();
    }

    private void initView() {
        family_list.addItemDecoration(new LinearSpacingItemDecoration(15, true));
        gateway_list.addItemDecoration(new LinearSpacingItemDecoration(10, true));
        SharedPreferences sp = getSharedPreferences("cloudAccount", Context.MODE_PRIVATE);
        mEditor = sp.edit();
        account = sp.getString("account", "");
        password = sp.getString("password", "");
        if (!account.equals("") && !password.equals("")) {
            account_edt.setText(account);
            password_edt.setText(password);
        }
        GateWayFactory gateWayFactory = GateWayFactory.getInstance();
        List<GateWay> gateWayList = gateWayFactory.getGateWayMode();
        if (gateWayList.isEmpty()) {
            GateWay gateWay = new GateWay();
            gateWay.setId(-1);
            gateWay.setGatewayName("无网关设备在线！");
            gateWayList.add(0, gateWay);
        }
        gateway_list.setAdapter(new GateWayAdapter(getApplicationContext(), gateWayList));
    }

    private void setListener() {
        back.setOnClickListener(this);
        familysSearchBtn.setOnClickListener(this);
        account_edt.setOnClickListener(this);
        password_edt.setOnClickListener(this);
        keyboard_number.setOnClickListener(this);
        input_one.setOnClickListener(this);
        input_two.setOnClickListener(this);
        input_three.setOnClickListener(this);
        input_four.setOnClickListener(this);
        input_five.setOnClickListener(this);
        input_six.setOnClickListener(this);
        input_seven.setOnClickListener(this);
        input_eight.setOnClickListener(this);
        input_nigh.setOnClickListener(this);
        input_zero.setOnClickListener(this);
        next_complete.setOnClickListener(this);
        delete.setOnClickListener(this);
        gatewaySearchBtn.setOnClickListener(this);
        delete.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                setEditText("-1");
                return true;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.input_one:
                setEditText("1");
                break;
            case R.id.input_two:
                setEditText("2");
                break;
            case R.id.input_three:
                setEditText("3");
                break;
            case R.id.input_four:
                setEditText("4");
                break;
            case R.id.input_five:
                setEditText("5");
                break;
            case R.id.input_six:
                setEditText("6");
                break;
            case R.id.input_seven:
                setEditText("7");
                break;
            case R.id.input_eight:
                setEditText("8");
                break;
            case R.id.input_nigh:
                setEditText("9");
                break;
            case R.id.input_zero:
                setEditText("0");
                break;
            case R.id.next_complete:
                if (account_edt.isFocused()) {
                    password_edt.requestFocus();
                } else {
                    password_edt.clearFocus();
                }
                break;
            case R.id.delete:
                setEditText("");
                break;
            case R.id.familysSearchBtn:
                gateway_layout.setVisibility(View.GONE);
                family_list.setVisibility(View.VISIBLE);
                if (keyboard_number.getVisibility() == View.VISIBLE) {
                    keyboard_number.setVisibility(View.GONE);
                }
                clearFocus();  //清理输入窗口焦点
                final KProgressHUD load = new ProgressDialogUtils().getLoadDialog(SpecifiedCloudFamily.this, "正在搜索");
                RetrofitUtil.retrofitCall().getClientFamilys(account, password).enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        JsonArray jsonArray = response.body().getAsJsonArray("data");
                        try {
                            Collection collection = JSONHelper.parseCollection(jsonArray.toString(), List.class, Archive.class);
                            if (!collection.isEmpty()) {
                                family_list.setVisibility(View.VISIBLE);
                                not_find.setVisibility(View.GONE);
                                familyAdapter = new FamilyAdapter(SpecifiedCloudFamily.this, (List) collection);
                                family_list.setAdapter(familyAdapter);
                                familyAdapter.mListener = new OnListItemClickListener<Archive>() {
                                    @Override
                                    public void setOnItemClick(Archive archive, int position) {
                                        String projectNameIn = archive.getProjectName();
                                        String projectKeyIn = archive.getProjectKey();
                                        String path = archive.getPath();
                                        downData(projectNameIn, projectKeyIn, path);
                                    }
                                };
                            } else {
                                not_find.setVisibility(View.VISIBLE);
                                family_list.setVisibility(View.GONE);
                            }
                            load.dismiss();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {
                        ToastPlus.showError("搜索失败，请检查网络");
                        load.dismiss();
                    }
                });
                break;
            case R.id.gatewaySearchBtn:
                gateway_layout.setVisibility(View.VISIBLE);
                family_list.setVisibility(View.GONE);

                break;
            default:
                account_edt.clearFocus();
                password_edt.clearFocus();
                break;
        }
    }

    //新服务器专案下载
    private void downData(final String projectName, String projectKeyIn, final String path) {
        DialogAlert alert = new DialogAlert(SpecifiedCloudFamily.this);
        alert.init(getString(R.string.tip), "是否下载此专案 ➡ [" + projectName + "]");
        alert.setSureListener(new DialogAlert.OnSureListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onSure() {
                final KProgressHUD downLoad = new ProgressDialogUtils().getLoadDialog(SpecifiedCloudFamily.this, "正在下载");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Call<ResponseBody> call = RetrofitUtil.retrofitCall().downMyFamily(path);
                        try {
                            Response response = call.execute();
                            CaseFileUtil.newCaseFile(response, projectName, false, 1);
                            Constants.path = path;  //把下载链接更新到全局,以便快速更新
                            downLoad.dismiss();
                            mHandler.sendMessage(mHandler.obtainMessage(0, "下载完成"));
                            Constants.isCheckProject = 0; //切换专案 指示变量
                            MyApplication.getInstance().updateFresh();
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        alert.show();
    }

    //清除焦点
    private void clearFocus() {
        if (account_edt.isFocused()) {
            account_edt.clearFocus();
        }
        if (password_edt.isFocused()) {
            password_edt.clearFocus();
        }
    }


    private void checkVersionUpdate() {
        //post请求获取最新的APP版本
        RetrofitUtil.retrofitCallHTTP().getApkVersion("BackgroundMusic").enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                String version = response.body().get("msg").getAsString();
                final String downPath = response.body().get("data").getAsString();
                if (Double.parseDouble(appVersion) < Double.parseDouble(version)) {
                    DialogAlert alert = new DialogAlert(SpecifiedCloudFamily.this);
                    alert.init("温馨提示", "是否更新到新版本" + version);
                    alert.setSureListener(new DialogAlert.OnSureListener() {
                        @Override
                        public void onCancel() {

                        }

                        @Override
                        public void onSure() {
                            final ProgressDialog dialog = new ProgressDialog(SpecifiedCloudFamily.this);
                            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                            dialog.setCancelable(false);
                            dialog.show();
                            new Thread(new DownloadApk(dialog, downPath)).start();
                        }
                    });
                    alert.show();
                } else {
                    ToastUtils.ShowSuccess(SpecifiedCloudFamily.this, "已经是最新版本！", 1000, true);
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                DialogAlert alert = new DialogAlert(SpecifiedCloudFamily.this);
                alert.init("温馨提示", "连接不到服务器，请检查网络");
            }
        });
    }


    /**
     * 给当前获取焦点的输入框输入文字
     */
    private void setEditText(String text) {
        if (account_edt.isFocused()) {
            int index = account_edt.getSelectionStart();
            switch (text) {
                case "":
                    if (account_edt.getText().toString().equals("") || index == 0) {
                        return;
                    }
                    account_edt.getText().delete(index - 1, index);
                    break;
                case "-1":
                    account_edt.getText().clear();
                    break;
                default:
                    account_edt.getText().insert(index, text);
                    break;
            }
        }
        if (password_edt.isFocused()) {
            int index = password_edt.getSelectionStart();
            switch (text) {
                case "":
                    if (password_edt.getText().toString().equals("") || index == 0) {
                        return;
                    }
                    password_edt.getText().delete(index - 1, index);
                    break;
                case "-1":
                    password_edt.getText().clear();
                    break;
                default:
                    password_edt.getText().insert(index, text);
                    break;
            }
        }
    }

    /**
     * 初始化输入框
     */
    private void initEditText() {
        disableShowInput(account_edt);
        disableShowInput(password_edt);
        account_edt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    //获取焦点
                    keyboard_number.setVisibility(View.VISIBLE);
                    family_list.setVisibility(View.GONE);
                    next_complete.setText("下一个");
                } else {
                    //失去焦点
                    keyboard_number.setVisibility(View.GONE);
                    account = account_edt.getText().toString();
                    mEditor.putString("account", account);
                }
                mEditor.apply();
            }
        });
        password_edt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    //获取焦点
                    keyboard_number.setVisibility(View.VISIBLE);
                    family_list.setVisibility(View.GONE);
                    next_complete.setText("完成");
                } else {
                    //失去焦点
                    keyboard_number.setVisibility(View.GONE);
                    password = password_edt.getText().toString();
                    mEditor.putString("password", password);
                }
                mEditor.apply();
            }
        });
    }

    /**
     * 设置输入框获取焦点是不弹出软键盘
     */
    private void disableShowInput(EditText et) {
        Class<EditText> cls = EditText.class;
        try {
            Method method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            method.setAccessible(true);
            method.invoke(et, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class DownloadApk implements Runnable {
        private ProgressDialog dialog;
        private String downPath;
        private InputStream is = null;
        private FileOutputStream fos = null;

        DownloadApk(ProgressDialog dialog, String downPath) {
            this.dialog = dialog;
            this.downPath = downPath;
        }

        @Override
        public void run() {
            OkHttpClient client = new OkHttpClient();
            Request.Builder builder = new Request.Builder();
            Request request = builder.get().url(downPath).build();
            try {
                okhttp3.Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    long contentLength = response.body().contentLength(); //获取内容总长度
                    dialog.setMax((int) contentLength); //设置最大值
                    File apkFile = new File("mnt/sdcard/Download/", "music.apk"); //保存到sd卡
                    fos = new FileOutputStream(apkFile); //获得输入流
                    is = response.body().byteStream();
                    byte[] bys = new byte[1024];  //定义缓冲区大小
                    int progress = 0;
                    int len = -1;
                    while ((len = is.read(bys)) != -1) {
                        try {
                            Thread.sleep(1);
                            fos.write(bys, 0, len);
                            fos.flush();
                            progress += len;
                            dialog.setProgress(progress);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    installApk(apkFile);   //下载完成,提示用户安装
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭IO流
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    is = null;
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fos = null;
                }
            }
            dialog.dismiss();
        }
    }

    private void installApk(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(apkFile.toString())), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }


}
